﻿using System.Collections.Generic;
using RenterClient.Models;
using System.Net.Http;
using System.Net.Http.Headers;
using RenterClient.Interfaces;
using System;
using System.Threading.Tasks;
using System.Text;
using System.Net;
using System.Web;
using System.Web.Mvc;
using RenterClient.Controllers;
using Newtonsoft.Json.Linq;

namespace RenterClient.Service
{
    public class RenterService : IRenterService
    {
        private static string apiURI = "http://localhost.:3000/";
        private MediaTypeWithQualityHeaderValue mediaType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded");
        private void HttpClientBuilder(HttpClient client)
        {
            client.BaseAddress = new Uri(apiURI);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(mediaType);
        }

        public async Task<List<PostModels>> GetAllPosts()
        {
            List<PostModels> posts = null;

            using (HttpClient client = new HttpClient())
            {
                HttpClientBuilder(client);

                try
                {
                    HttpResponseMessage response = await client.GetAsync("posts");
                    if (response.IsSuccessStatusCode)
                    {
                        posts = await response.Content.ReadAsAsync<List<PostModels>>();
                    }
                }
                catch (HttpRequestException e)
                {
                    // TODO
                    throw e;
                }
            }

            return posts;
        }

        public async Task<PostModels> GetPost(string id, string connectID)
        {
            PostModels post = new PostModels();

            using (HttpClient client = new HttpClient())
            {
                HttpClientBuilder(client);

                try
                {
                    using (HttpClientHandler handler = new HttpClientHandler { UseCookies = false })
                    {
                        using (HttpClient clientTest = new HttpClient(handler) { BaseAddress = new Uri(apiURI) })
                        {
                            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get, "posts/" + id);
                            
                            message.Headers.Add("Cookie", "connect.sid=" + connectID);
                            HttpResponseMessage response = await clientTest.SendAsync(message);

                            if (response.IsSuccessStatusCode)
                            {
                                post = await response.Content.ReadAsAsync<PostModels>();
                            }
                            else if (Convert.ToInt32(response.StatusCode) == 401)
                            {
                                return null;
                            }
                        }
                    }
                }
                catch (HttpRequestException e)
                {
                    // TODO
                    throw e;
                }
            }

            return post;
        }

        public async Task<List<PostModels>> GetSearchedPosts(PlaceModels place)
        {
            List<PostModels> posts = null;
            using (HttpClient client = new HttpClient())
            {
                HttpClientBuilder(client);
                try
                {
                    //HttpContent content = new FormUrlEncodedContent(place);
                    JObject jObject = new JObject(place);
                    StringContent stringContent = new StringContent(jObject.ToString());
                    HttpResponseMessage response = await client.PostAsync("posts", stringContent);
                }
                catch (Exception)
                {
                    
                    throw;
                }
            }
            // TODO 1: call api for searched post
            // TODO 2: manage creadentials and request callback
            return posts;
        }

        public async Task<HttpResponseMessage> Authentication(string username, string password)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpClientBuilder(client);

                try
                {
                    StringBuilder content = new StringBuilder().Append("email=").Append(username).Append("&password=").Append(password);
                    string authenticationContent = Convert.ToString(content);

                    HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, "authentication");
                    req.Content = new StringContent(authenticationContent, Encoding.UTF8, "application/x-www-form-urlencoded");

                    return await client.SendAsync(req);
                }
                catch (Exception ex)
                {

                    throw ex;
                }
            }
        }


    }
}